<?php

// +----------------------------------------------------------------------

namespace app\mall\home;

use app\index\controller\Home;
use app\user\model\User as UserModel;
use app\mall\model\Goods as GoodsModel;
use app\mall\model\Order as OrderModel;
use app\mall\model\Store as StoreModel;
use app\mall\model\Cart as CartModel;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use app\mall\model\Refund;
use think\facade\Db;


/**
 * 订单控制器
 * @package app\mall\home
 */
class Order extends Home
{
    public function index($status = 99)
    {
		//查找用户信息
		$uid = is_login();
		$map = [
			['uid', '=',  $uid],
			['trash', '=',  0],
		];
		$order = 'create_time desc';
		if ($status != 99) $map[] = ['status', '=',  $status];		
		$data_list = OrderModel::pageList($map,$order, 'full', 6, 'api');
		if (request()->isPost()){
			$ajax = $data_list->items();
			$data['items'] = $ajax;
			$data['last_page'] = $data_list->lastPage();
			$data['total'] = $data_list->total();
			$this->success('加载成功', '', $data);
		}
		
		// 获取类型
		$status = OrderModel::status();
		$status_list = [
			['id' => 99, 'title' => '全部'],
		];
		foreach ($status as $k => $v) {
			$status_list[] = [
				'id'	=> $k,
				'title'	=> $v,
			];
		}
		$this->assign('status', $status_list);
		// 分享参数
		$share = [
			'title' => '我的订单',
			'desc'	=> '商城订单列表',
			'url'	=> real_url('mall/order/index'),
		];
		$this->assign('share', $share);
		
		// 获取购物车数量
		$user['cart'] = CartModel::where('uid', $uid)->count('id');
		$this->assign('user', $user);
		//重新定义active
		$this->view->active = 'member';
		return $this->fetch(); // 渲染模板
    }
	public function detail($id = 0)
	{
		if (request()->isPost()){
			if ($id == 0) $this->error('参数错误');
			//查找用户信息
			$uid = is_login();
			$map = [
				['uid', '=',  $uid],
				['id', '=',  $id],
				['trash', '=',  0],
			];
			$order = OrderModel::where($map)->find();
			if (!$order) {
				$this->error('未找到该订单');
			}
			$data_list = Db::view('mall_order_detail', true)
			    ->view("mall_goods", ['title','price','logo'], 'mall_goods.id=mall_order_detail.gid', 'left')
			    ->where('mall_order_detail.oid', '=', $order['id'])
			    ->order('mall_order_detail.gid')
			    ->select();
			if (!$data_list) $this->error('订单信息错误');
			$data_list = $data_list->toArray();
			foreach ($data_list as $key => $value) {
				$data_list[$key]['cover'] = get_file_path($value['logo']);
				$data_list[$key]['price'] = $value['price'] * $value['number']/ 100;
				$data_list[$key]['discount'] = $value['discount'] . '%';
				$data_list[$key]['pay_price'] = $value['pay_price'] / 100;
				$data_list[$key]['balance'] = $value['balance'] / 100;
				$data_list[$key]['second'] = $value['second'] / 100;
				$data_list[$key]['realpay'] = $value['realpay'] / 100;
			}
			$order['list'] = $data_list;
			$order['count'] =  count($data_list);
			$order['status_txt'] = OrderModel::status($order['status']);
			if ($order['status'] == 0){
				$order['tips'] = '请在'.format_time($order['create_time'] + 1800).'之前完成支付';
			} else {
				$order['tips'] = '订单于'.format_time($order['pay_time']).'完成支付';
			}
			$order['express_url'] = false;
			if ($order['status'] > 1) {
				$order['express_url'] = 'https://m.kuaidi100.com/app/query/?com='.$order['ex_com'].'&nu='.$order['express'].'&coname='. urlencode(real_url('mall/order/detail', ['id' => $id]));
				$order['ex_com'] = OrderModel::express($order['ex_com']);
			}
			$order['create_time'] = format_time($order['create_time']);
			$order['update_time'] = format_time($order['update_time']);
			$order['pay_time'] = $order['pay_time'] == 0 ? 0 : format_time($order['pay_time']);
			$order['pay_price'] = $order['pay_price'] / 100;
			$order['balance'] = $order['balance'] / 100;
			$order['second'] = $order['second'] / 100;
			$order['realpay'] = $order['realpay'] / 100;
			$order['address'] = VipModel::getAddress($uid);
			$this->success('请求成功', '', $order);
		}
		// 分享参数
		$share = [
			'title' => '订单详情',
			'desc'	=> '商城订单列表',
			'url'	=> real_url('mall/order/index'),
		];
		$this->assign('share', $share);
		
		return $this->fetch(); // 渲染模板
	}
	/**
	 * 删除订单
	 * param int $id 订单ID
	 * return bool
	 **/
	public function delete($id = 0)
	{
		if($id === 0) $this->error('参数错误！');
		
		$uid = is_login();
		// 获取订单信息
		$order = OrderModel::where('id', '=', $id)->where('uid', '=', $uid)->where('status', '<', 2)->find();
		if($order){
			// 实例化
			$order = new OrderModel;
			$return =  $order->cancel($id);
			if ($return === false) {
				$this->error($order->getError());
			}else{
				$this->success('撤销成功');
			}
		}else{
			$this->error('该订单不可撤销');
		}
	}
	/**
	 * 生成订单
	 * param int $ids 购物车ID
	 * return url
	 **/
	public function create($ids = '')
	{
		if (request()->isPost()){

			$param = request()->post();
			if(!isset($param['ids'])) $this->error('参数错误！');
			$ids = is_array($param['ids']) ? $param['ids'] : (array)$param['ids'];
			// 实例化
			$order = new OrderModel;
			$return =  $order->createOrder($ids);

			if ($return === false) {
				$this->error($order->getError());
			}else{
			    $map['send_status'] = 1;
			    $data_list = UserModel::where($map)
                    ->order('sort asc,id asc')
                    ->select();
                $adminuser_list = $data_list->toArray();
                $orderarr = $order->where('id', $return)->find();
                foreach ($adminuser_list as $v){
                    
                    if(!empty($v['openid'])){
                        $sendData = [
                            'template_id'   => '1aYunv430Dy6I0fe8Tc7gQbSd41i9dljUF8f5pkNL0c',//模板消息ID
                            'touser'    => $v['openid'],//用户openid：o25FHswdGhUZSuLR12d_UXreGr3w
                            'data'=>[
                                'first'=>[
                                    'value'=>'您有新的订单待处理',
                                    'color'=>'#000000',
                                ],
                                'keyword1'=>[
                                    'value'=>'订单编码：'.$orderarr['id'],//订单编号
                                    'color'=>'#000000'
                                ],
                                'keyword2'=>[//订单金额
                                    'value'=>number_format($orderarr['realpay']/100,2),
                                    'color'=>'#000000'
                                ],
                                'keyword3'=>[//创建时间
                                    'value'=>date('Y-m-d H:i:s',$orderarr['create_time']),
                                    'color'=>'#000000'
                                ],
                                'remark'=>[
                                    'value'=>'新的订单！',//描述
                                    'color'=>'#173177',
                                ],
                            ]
                        ];
                        $this->template($sendData);
                    }
                }

				$this->success('下单成功', real_url('mall/order/detail', ['id' => $return]));
			}
		}
		$this->success('调取成功');
	}

	/**
	 * 订单支付
	 * param int $pid 订单总ID
	 * return array 支付参数
	 **/
	public function pay($id = 0)
	{
		if($id === 0) $this->error('参数错误！');
		
		$uid = is_login();
		
		// 获取订单信息
		$order = OrderModel::where('id', $id)->where('uid', $uid)->where('status', 0)->find();

		if($order){
			// 实例化
			$order = new OrderModel;
			$return =  $order->payOrder($id);
			if ($return === false) {
				$msg = $order->getError();
				if ($msg == 'success') {
					$status = [
						'code' 	=> 200,
						'msg'	=> '支付成功',
					];
					return json($status);
				}
				$this->error($order->getError());
			}else{
                $map['send_status'] = 1;
                $data_list = UserModel::where($map)
                    ->order('sort asc,id asc')
                    ->select();
                $adminuser_list = $data_list->toArray();
                foreach ($adminuser_list as $v){

                    if(!empty($v['openid'])){
                        $sendData = [
                            'template_id'   => 'n79Uydcf86ePu0GlwQyW-pa36tTBe5-jPgVAQkq9RSw',//模板消息ID
                            'touser'    => $v['openid'],//用户openid
                            'data'=>[
                                'first'=>[
                                    'value'=>'我们已收到您的货款，开始为您打包商品，请耐心等待: )',
                                    'color'=>'#000000',
                                ],
                                'orderMoneySum'=>[
                                    'value'=>number_format($return['amount']/100,2),//支付金额
                                    'color'=>'#000000'
                                ],
                                'orderProductName'=>[//商品信息
                                    'value'=>'订单编号：'.$return['out_trade_no'],
                                    'color'=>'#000000'
                                ],
                                'remark'=>[
                                    'value'=>'欢迎下次选购！',//描述
                                    'color'=>'#173177',
                                ],
                            ]
                        ];
                        $this->template($sendData);
                    }
                }
                $sendData = [
                    'template_id'   => 'n79Uydcf86ePu0GlwQyW-pa36tTBe5-jPgVAQkq9RSw',//模板消息ID
                    'touser'    => $return['openid'],//用户openid
                    'data'=>[
                        'first'=>[
                            'value'=>'我们已收到您的货款，开始为您打包商品，请耐心等待: )',
                            'color'=>'#000000',
                        ],
                        'orderMoneySum'=>[
                            'value'=>number_format($return['amount']/100,2),//支付金额
                            'color'=>'#000000'
                        ],
                        'orderProductName'=>[//商品信息
                            'value'=>'订单编号：'.$return['out_trade_no'],
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'欢迎下次选购！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);
				$this->success('预支付下单成功', '', $return);
			}
		}else{
			$this->error('订单已失效,或不可支付');
		}
	}
	/**
	 * 申请退换货
	 * param int $oid 订单ID
	 * param int $type 类型 1退货；2换货
	 * param int $desc 退换货说明
	 * return int status 返回状态
	 **/
	public function refund()
	{
		$param = $this->request->param();
		if(!isset($param['pid'])) $this->error('订单号错误！');
		$param['type'] = 1;
		$uid = is_signin();
		$param['uid'] = $uid;
		// 订单信息
		$order_list = OrderModel::where('pid', $param['pid'])->where('uid', $uid)->select();
		if($order_list){
			foreach ($order_list as $key => $order){
				$refund = Refund::where('oid', $order['id'])->find();
				if($refund) $this->error('请勿重复发起退换货');
				$param['money'] = $order['balance'] + $order['pay'];
				$param['number']	= $order['number'];
				$param['oid']		= $order['id'];
				$refund = Refund::create($param);
			}
		}else{
			$this->error('订单信息错误');
		}
	    $this->success('申请成功!', $refund);
	}
	/**
	 * 确认收货
	 * param int $oid 订单ID
	 * return int status 返回状态
	 **/
	public function action($id = 0)
	{
		if($id === 0) $this->error('参数错误！');
		
		$uid = is_login();
		// 获取订单信息
		$orders = OrderModel::where('id', '=', $id)->where('uid', '=', $uid)->where('status', '=', 2)->find();
		if($orders){
			// 实例化
			$order = new OrderModel;
			$return =  $order->action($id);

			if ($return === false) {
				$this->error($order->getError());
			}else{
                $payer = MemberModel::getOpenid($uid);//openid
                $list = Db::view('mall_order_detail', true)
                    ->view("mall_goods", ['title','price','logo'], 'mall_goods.id=mall_order_detail.gid', 'left')
                    ->where('oid', '=', $id)
                    ->select()
                    ->toArray();
//                var_dump($list);exit;
                $sendData = [
                    'template_id'   => 'sahhsoma1XrvcNRfMqHENv0dLh4QSVToVWEiH7h3SMA',//模板消息ID
                    'touser'    => $payer,//用户openid：o25FHswdGhUZSuLR12d_UXreGr3w
                    'data'=>[
                        'first'=>[
                            'value'=>'感谢您再次光临安合元！',
                            'color'=>'#000000',
                        ],
                        'keyword1'=>[
                            'value'=>$orders['out_trade_no'],//订单编号
                            'color'=>'#000000'
                        ],
                        'keyword2'=>[//商品信息
                            'value'=>$list[0]['title'],
                            'color'=>'#000000'
                        ],
                        'keyword3'=>[
                            'value'=>date('Y-m-d H:i:s',time()),//完成时间
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'订单已完成，欢迎下次选购！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);

				$this->success('收货成功');
			}
		}else{
			$this->error('该订单不可收货');
		}
	}
	/**
	 * 退换货运单号
	 * param int $oid 订单ID
	 * param int $tracking 运单号
	 * return array  返回数组
	 **/
	public function track()
	{
		$param = $this->request->param();
		if(!isset($param['oid'])) $this->error('订单号错误！');
		if(!isset($param['tracking'])) $this->error('运单号错误');
		if($param['tracking'] == '') $this->error('运单号必填');
		$uid = $this->getUserId();
		// 订单信息
		$refund = RefundModel::where('oid', $param['oid'])->where('uid', $uid)->where('status', 2)->find();
		if($refund){
			$refund->tracking = $param['tracking'];
			$refund->status = 3; //更改为待退款
			$refund->save();
		}else{
			$this->error('退货信息错误');
		}
	    $this->success('提交成功!', $refund);
	}
}
